package com.mes.common.datashard.util;

import com.mes.common.core.utils.SpringContextUtils;
import com.mes.common.core.utils.StringUtils;
import com.mes.common.datashard.exception.ShardException;
import com.mes.common.datashard.mapper.DataShardMapper;
import com.mes.common.datashard.strategy.TableShardStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.DataSource;
import java.util.List;
import java.util.Map;

@Component
public class TableShardSelector {

    @Autowired
    private Map<String, TableShardStrategy> selector;


    public TableShardStrategy select(String type) {
        return selector.get(type);
    }

    public boolean containsTable(String owner, String tableName) {
        DataSource dataSource = SpringContextUtils.getBean(DataSource.class);
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        //验证表是否存在
        List<String> list = jdbcTemplate.queryForList(" SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER =" + "'" + owner + "'" + " AND TABLE_NAME =" + "'" + tableName + "'", String.class);
        return !list.isEmpty();
    }

    @Transactional
    public void createTable(String fileName, String owner, String tableName) throws Exception {
        DataSource dataSource = SpringContextUtils.getBean(DataSource.class);
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        // 1. 读取SQL文件
        List<String> sqlScripts = SqlFileReader.readSqlFile(fileName + ".sql");
        if (sqlScripts.isEmpty()) {
            throw new ShardException("SQL文件为空");
        }
        // 2. 替换SQL中的模式名称 表名
        for (int i = 0; i < sqlScripts.size(); i++) {
            String sqlScript = sqlScripts.get(i);
            String finalSql = sqlScript.replace("{owner}", owner);
            finalSql = finalSql.replace("{tableName}", tableName) + ";";
            jdbcTemplate.execute(finalSql);
        }
    }
}
